import { COS_HOST } from '@/constants';
import { downloadFileUsingGet, uploadFileUsingPost } from '@/services/cos-demo/fileController';
import { InboxOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { UploadProps } from 'antd';
import { Button, Card, Divider, Flex, message, Upload } from 'antd';
import { saveAs } from 'file-saver';
import React, { useState } from 'react';

const { Dragger } = Upload;

/**
 * 主页
 *
 * @constructor
 */
const Index: React.FC = () => {
  const [value, setValue] = useState<string>();
  const props: UploadProps = {
    name: 'file',
    multiple: false,
    maxCount: 1,
    customRequest: async (fileObj: any) => {
      try {
        const res = await uploadFileUsingPost({}, fileObj.file);
        fileObj.onSuccess(res.data);
        setValue(res.data);
      } catch (e: any) {
        message.error(e.message);
        fileObj.onError(e);
      }
    },
    onRemove: () => {
      setValue(undefined);
    },
  };

  return (
    <PageContainer className="index">
      <Flex gap={16}>
        <Card title="文件上传" style={{ width: 700 }}>
          <Dragger {...props}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">单击或拖动文件到此区域</p>
            <p className="ant-upload-hint">支持单次或批量上传</p>
          </Dragger>
        </Card>
        <Card title="文件下载" style={{ width: 425 }}>
          <div>文件地址：{value ? value : '暂无'}</div>
          <Divider />
          <img src={value ? COS_HOST + value : undefined} height={200} />
          <Divider />
          <Button
            onClick={async () => {
              const blob = await downloadFileUsingGet(
                { filepath: value },
                {
                  responseType: 'blob',
                },
              );
              // 使用 file-saver 下载文件
              const fullPath = COS_HOST + value;
              // saveAs(返回的流, 文件名);
              saveAs(blob, fullPath.substring(fullPath.lastIndexOf('/') + 1));
            }}
          >
            点击下载文件
          </Button>
        </Card>
      </Flex>
    </PageContainer>
  );
};

export default Index;
